﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;

namespace BoYuan.MvcCodeTemplates.FineUIMvc.Template
{
    public class ControllerTemplate: FineuiBase
    {
        public static string GetCode(TableModel tb)
        {
            List<DbColumnInfo> list = tb.Columns;
            DbColumnInfo keyModel = list.FirstOrDefault(p => p.IsPrimarykey == true);
            List<DbColumnInfo> list2 = list.Where(p => p.IsPrimarykey == false).ToList();//非主键列
            if (keyModel == null) { throw new Exception("表没有主键，没办法生成代码！ControllerTemplate"); }

            //add 相关
            StringBuilder sb2 = new StringBuilder();//赋值
            //StringBuilder sb3 = new StringBuilder();//int验证
            StringBuilder sb4 = new StringBuilder();//update要更新的字段
            StringBuilder sb5 = new StringBuilder();//insert要赋值的字段

            //bool haveDefaultValue;//是否有默认值
            foreach (var colm in list2)
            {
                //haveDefaultValue = colm.DefaultValue.Length > 0;
                switch (colm.DataType.ToLower())
                {
                    case "bit":
                        sb2.AppendLine(string.Format("            mo.{0}=Convert.ToBoolean(fc[\"f_{0}\"]); ", colm.DbColumnName));

                        sb4.Append(",p." + colm.DbColumnName);
                        break;
                    case "datetime":
                        if (colm.DefaultValue.IndexOf("getdate()", StringComparison.InvariantCultureIgnoreCase) >= 0)
                        {
                            //有默认值，添加时候需要赋值，更新不需要修改
                            sb5.AppendLine(string.Format("                mo.{0} = DateTime.Now;", colm.DbColumnName));
                        }
                        else //没有默认值，需要手动添加
                        {
                            sb2.AppendLine(string.Format("            " + (colm.IsNullable ? "if (DateTime.TryParse(fc[\"f_{0}\"], out var {0}TempResult))" : string.Empty) + "mo.{0} = Convert.ToDateTime(fc[\"f_{0}\"]);", colm.DbColumnName));

                            sb4.Append(",p." + colm.DbColumnName);
                        }
                        break;
                    case "bigint":
                        sb2.AppendLine(string.Format("            " + (colm.IsNullable ? "if (long.TryParse(fc[\"f_{0}\"], out var {0}TempResult))" : string.Empty) + "mo.{0}= Convert.ToInt64(fc[\"f_{0}\"]); ", colm.DbColumnName));

                        sb4.Append(",p." + colm.DbColumnName);
                        break;
                    case "tinyint":
                        sb2.AppendLine(string.Format("            " + (colm.IsNullable ? "if (byte.TryParse(fc[\"f_{0}\"], out var {0}TempResult))" : string.Empty) + "mo.{0}= Convert.ToByte(fc[\"f_{0}\"]); ", colm.DbColumnName));

                        sb4.Append(",p." + colm.DbColumnName);
                        break;
                    case "smallint":
                        sb2.AppendLine(string.Format("            " + (colm.IsNullable ? "if (short.TryParse(fc[\"f_{0}\"], out var {0}TempResult))" : string.Empty) + "mo.{0}= Convert.ToInt16(fc[\"f_{0}\"]); ", colm.DbColumnName));

                        sb4.Append(",p." + colm.DbColumnName);
                        break;
                    case "int":
                        sb2.AppendLine(string.Format("            " + (colm.IsNullable ? "if (int.TryParse(fc[\"f_{0}\"], out var {0}TempResult))" : string.Empty) + "mo.{0}= Convert.ToInt32(fc[\"f_{0}\"]); ", colm.DbColumnName));

                        sb4.Append(",p." + colm.DbColumnName);
                        break;
                    case "money":// break;
                    case "decimal":
                        sb2.AppendLine(string.Format("            " + (colm.IsNullable ? "if (decimal.TryParse(fc[\"f_{0}\"], out var {0}TempResult))" : string.Empty) + "mo.{0}= Convert.ToDecimal(fc[\"f_{0}\"]); ", colm.DbColumnName));

                        sb4.Append(",p." + colm.DbColumnName);
                        break;
                    case "real":
                        sb2.AppendLine(string.Format("            " + (colm.IsNullable ? "if (float.TryParse(fc[\"f_{0}\"], out var {0}TempResult))" : string.Empty) + "mo.{0}= Convert.ToSingle(fc[\"f_{0}\"]); ", colm.DbColumnName));

                        sb4.Append(",p." + colm.DbColumnName);
                        break;
                    case "float":
                        sb2.AppendLine(string.Format("            " + (colm.IsNullable ? "if (double.TryParse(fc[\"f_{0}\"], out var {0}TempResult))" : string.Empty) + "mo.{0}= Convert.ToDouble(fc[\"f_{0}\"]); ", colm.DbColumnName));

                        sb4.Append(",p." + colm.DbColumnName);
                        break;
                    default:
                        sb2.AppendLine(string.Format("            mo.{0}= fc[\"f_{0}\"]; ", colm.DbColumnName));

                        sb4.Append(",p." + colm.DbColumnName);
                        break;
                }
            }

            string updateColumns = "p => new {" + sb4.ToString().Substring(1) + "}";

            string code = string.Format(@"
using FineUIMvc;
using SqlSugar;
using System;
using System.Linq;
using System.Web.Mvc;
using {9}.DBServices;
using {0}.Controllers;

namespace {0}.Areas.{1}.Controllers
{{
    public partial class {2}Controller : {4}
    {{
        #region ListPage
        // GET: {1}/{2}
        public ActionResult Index()
        {{
            return View();
        }}

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Grid1_PageIndexChanged(FormCollection fc)
        {{
            var db = DB_Base.Instance;

            //此处代码不能设置断点debug。
            var queryable = db.Queryable<{5}.{2}>()
                //todo 筛选
                //.WhereIF(fc[""txb_keyword""].Trim().Length > 0, p=> )
                .OrderBy(p => p.{3})
                .Select<{5}.{2}>() ;

            var grid1 = UIHelper.Grid(""Grid1"");
            grid1.BindGrid(fc, ""ddlPageSize"", queryable);
            return UIHelper.Result();
        }}

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Button_delete_Click(string ids)
        {{
            var idList = Array.ConvertAll<string, int>(ids.Substring(1).Split(','), int.Parse);
            if (idList.Length == 0)
            {{
                NotifyQuestion(""请选择要删除的选中行！"");
            }}
            else
            {{
                var db = DBServices.DB_Base.Instance;
                db.Deleteable<{5}.{2}>(p => idList.Contains(p.{3})).ExecuteCommand();
                AlertSuccess(""删除成功！"", false, ""onGridBind()"");
            }}
            return UIHelper.Result();
        }}
        #endregion

        #region AddPage

        public ActionResult Add()
        {{
            if (int.TryParse(Request[""id""],out int id))//编辑页面初始化
            {{
                {5}.{2} mo = DBServices.DB_Base.GetModel<{5}.{2}>(id);

                return View(mo);
            }}
            return View();//添加页面
        }}

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Button_save_OnClick(FormCollection fc)
        {{
            bool isEdit = int.TryParse(fc[""f_{3}""], out int {3});

            {5}.{2} mo = new {5}.{2}();
            {6}

            if (!isEdit)//添加
            {{
{8}
                if (DBServices.DB_Base.InsertModel(mo) > 0)
                {{
                    AlertInfor(""添加成功"", true);
                }}
                else
                {{
                    NotifyError(""添加失败"");
                }}
            }}
            else//修改
            {{
                int returnNum= DBServices.DB_Base.UpdateModels(mo, 
                           //注意更新字段是否对应，数量是否一致 
{7},
                           //条件
                           p => p.{3}=={3});
                if (returnNum>0)
                {{
                    AlertInfor(""修改成功"", true);
                }}
                else
                {{
                    NotifyError(""修改失败"");
                }}
            }}
            return UIHelper.Result();
        }}
        #endregion

    }}
}}
"
                ,tb.NamespaceStr            //0
                ,tb.Namespace2Str           //1
                ,tb.TableName               //2
                ,keyModel.DbColumnName      //3
                ,tb.ClassnameStr            //4
                ,tb.ModelName               //5
                ,sb2.ToString()             //6
                ,updateColumns              //7
                ,sb5.ToString()             //8
                ,tb.ModelName.Split('.')[0]                //9
                );
            return code;
        }
    }
}
